package InternetCode.Socket.Exa8;


import java.io.*;
import java.net.*;
import java.util.Scanner;

/**
 * 实现客户端和服务器端的双端通信
 */
public class ServerSocketFrame{
    private PrintWriter writer; // 声明PrintWriter类对象
    private BufferedReader reader; // 声明BufferedReader对象
    private ServerSocket server; // 声明ServerSocket对象
    private Socket socket; // 声明Socket对象socket
    private Scanner scanner;

    public void getServer() {
        try {
            server = new ServerSocket(1978); // 实例化Socket对象
            System.out.println("服务器套接字已经创建成功\n"); // 输出信息
            while (true) { // 如果套接字是连接状态
                System.out.println("等待客户机的连接......\n"); // 输出信息
                socket = server.accept(); // 实例化Socket对象
                reader = new BufferedReader(new InputStreamReader(socket
                        .getInputStream())); // 实例化BufferedReader对象
                writer = new PrintWriter(socket.getOutputStream(), true);
                getClientInfo(); // 调用getClientInfo()方法
            }
        } catch (Exception e) {
            e.printStackTrace(); // 输出异常信息
        }
    }

    private void getClientInfo() {
        try {
            while (true) { // 如果套接字是连接状态
                String line = reader.readLine();
                if (line != null)
                    System.out.println("接收到客户机发送的信息：" + line + "\n"); // 获得客户端信息
            }
        } catch (Exception e) {
            System.out.println("客户端已退出。\n"); // 输出异常信息
        } finally {
            try {
                if (reader != null) {
                    reader.close();// 关闭流
                }
                if (socket != null) {
                    socket.close(); // 关闭套接字
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendInfoToClient(){
        while(true){
            scanner=new Scanner(System.in);
            System.out.println("请输入要发送的消息:");
            String text=scanner.nextLine();
            if(text.equals("quit")){
                break;
            }
            writer.println(text);
        }
    }


    public static void main(String[] args) { // 主方法
        ServerSocketFrame frame = new ServerSocketFrame(); // 创建本类对象
        //此线程用于监听接收消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                frame.getServer();
            }
        }).start();
        //此线程用发送消息给客户端
        new Thread(new Runnable() {
            @Override
            public void run() {
                frame.sendInfoToClient();
            }
        }).start();
    }


}